import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {AtRate, AtTextarea} from "taro-ui";
import {h5Wx} from "../../utils/h5.service";
import {Block, Checkbox, Image, ScrollView, Text, View} from "@tarojs/components";
import './evaluation.scss'
import {
  RESOURCE_URL,
  BASE_URL,
  materialMedia,
  TARO_ENV,
  UPLODE_FALE,
  GOODS_EVALUATION_APP_SAVE,
  GOODS_EVALUATION_APP_EDIT,
} from "../../constants/api";
import {http} from "../../utils/http";
import {newHttp} from "../../utils/request";
import {user} from "../../utils/user.service";
import {GetRequest, vcmonitor} from "../../utils/tools";
import {lxH5Wx} from "../../utils/lx.h5.service";

export default class Evaluate extends Component {
  state: {
    env: string
    bottomView: string
    content: string
    files: any
    goods: any
    orderNum: string
    formData: object
    star: number
    isAnonymous: boolean
    flag: number
  } = {
    env: '',
    bottomView: '',
    content: '',
    files: [],
    goods: {},
    formData: {
      resource_urls: '',
      content: '',
      order_num: ''
    },
    star: 0,
    isAnonymous: false,
    flag: 0
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.setState({env: process.env.TARO_ENV})
  }

  async componentDidShow() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    vcmonitor(this)
    const orderNum = Taro.getCurrentInstance().router.params.orderNum
    const {formData} = this.state
    const res = await http.HPost(GOODS_EVALUATION_APP_EDIT + orderNum, {})
    if (res) {
      formData.order_num = orderNum
      this.setState({
        goods: res.data,
        formData
      })
    }
  }

  handleChange(content) {
    this.setState({content})
  }

  async uploadFile() {
    const api = BASE_URL + UPLODE_FALE
    const that = this
    const {files} = this.state
    if (TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (f, length) => {
          lxH5Wx.uploadFile(f, length, (data) => {
            files.push({url: data})
            that.setState({files, bottomView: `bottomView${files.length - 1}`})
          })
        }, 1)
      } else {
        await h5Wx.chooseImage(1, async ret => {
          await Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          await h5Wx.wxuploadImage(ret, async res => {
            const data = await newHttp.catchGet(materialMedia + res, {})
            files.push({url: data})
            that.setState({files, bottomView: `bottomView${files.length - 1}`})
            Taro.hideToast();
          })
        })
      }
    } else {
      Taro.chooseImage({
        count: 1,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: (res) => {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                files.push({url: data.imageUrl})
                that.setState({files, bottomView: `bottomView${files.length - 1}`})
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  setTimeout(() => {
                    Taro.hideToast();
                  }, 2000)
                }
              },
              fail: function (res) {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false
                })
              }
            });
          }
        }
      })
    }
  }

  agree() {
    const {isAnonymous} = this.state
    this.setState({isAnonymous: !isAnonymous})
  }

  handleChangeStar(k) {
    let {star, flag} = this.state
    if (flag == k) { // 第二次点击，为半颗星
      if (star == k - 0.5) { // 第二次点击，并且此时已经是半颗星的状态话，再次变成一颗星
        star = k
      } else {
        star = k - 0.5
      }
    } else {
      star = k // 首次点击，为整颗星
    }
    this.setState({
      star: star,
      flag: k
    })
  }

  signEvaluation() {
    const {files, content, env, formData} = this.state
    Taro.showLoading({title: '提交中...'})
    if (files && files.length > 0) {
      files.map((item, index) => {
        formData.resource_urls += item.url
        if (index < files.length - 1) {
          formData.resource_urls += ","
        }
      })

    }
    formData.content = content
    formData.is_anonymous = this.state.isAnonymous ? 1 : 0
    formData.star = this.state.star
    this.setState({formData}, async () => {
      Taro.showLoading({title: '提交中...'})
      const ret = await http.HPost(GOODS_EVALUATION_APP_SAVE, this.state.formData)
      Taro.hideLoading()
      this.setState({submiting: false})
      if (ret.data.isOk) {
        Taro.showModal({
          content: '已提交审核, 审核通过后会显示出来',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              Taro.navigateBack()
            }
          }
        })
      } else {
        this.setState({submiting: false})
      }
    })
  }

  removeFile(index) {
    const {files} = this.state
    files.splice(index, 1)
    this.setState({files})
  }

  render() {
    const {content, files, goods, bottomView, star} = this.state
    return (
      <View className='evaluation-wrapper'>
        <GzhAuth />
        <View className='evaluation-wrapper-content'>
          <View className='product-info'>
            <View className='img'><Image className='image'
              src={goods.modelImg}
              mode='aspectFill'
            /></View>
            {goods.order && <View className='product-right'>
              <View className='name'>{goods.order.product_name}</View>
              <View className='nums'>x{goods.order.buy_amount}</View>
            </View>}
          </View>
          <AtTextarea className='car text-area' maxLength={100} value={content} onChange={this.handleChange.bind(this)}
            placeholder='您有体验新的要分享给想买的他们吧'
          />
          <View className='upload-file'>
            {files && files.length > 0 && <View className='files-left'>
              <ScrollView scrollX enableFlex className='files' scrollWithAnimation scrollIntoView={`${bottomView}`}>
                {files.map((item, index) => <View className='file-img' id={`bottomView${index}`}>
                  <Image mode='aspectFill' className='image' src={item.url} />
                  <View className='close' onClick={this.removeFile.bind(this, index)}>
                    <Image className='upload-file-images'
                      src='https://resource.ivcheng.com/upload/images/c2d1d9da-1d3d-4b6c-9a83-f8bddbedda72.jpg'
                      onClick={this.uploadFile.bind(this)}
                    />
                  </View>
                </View>)}
              </ScrollView>
            </View>}
            <View className='files-right' onClick={this.uploadFile.bind(this)}>
            </View>
          </View>
        </View>
        {(process.env.P_ENV === 'vc' || process.env.P_ENV === 'kunxin') && goods.site &&
        <View className='evaluation-wrapper-content evaluation'>
          <View className='header'>
            <View className='title'>
              <Image mode='aspectFill' className='title-img' src={RESOURCE_URL + goods.site.logo}><View
                className='title-image'
              /></Image>
              {goods.site && <View className='user-name'>
                {goods.site.name}
              </View>}
            </View>
            <View className='agree'>
              <Checkbox className='check-box-width' value='true' onClick={this.agree.bind(this)} />
              <Block>
                <Block>
                  <Text>匿名评价</Text>
                </Block>
              </Block>
            </View>
          </View>
          <View className='star'>
            <AtRate
              margin={30}
              value={star}
              onChange={this.handleChangeStar.bind(this)}
            />
          </View>
        </View>}
        <View
          style={`color:#fff;border: 1px solid ${process.env.mainColor} !important;background-color:${process.env.mainColor}`}
          className='sign-evaluation' onClick={this.signEvaluation.bind(this)}
        >
          发表评价
        </View>
      </View>
    )
  }
}
